<template>
  <BasicModal
    @register="register"
    :destroyOnClose="true"
    title="符合筛选器"
    @ok="save"
    :body-style="{ marginLeft: '10px', marginRight: '10px' }"
    width="600px"
  >
    <span>操作:</span>
    <Select class="!w-full mt-12px" v-model:value="cond.predicate.operation" :disabled="isDisable">
      <SelectOption value="AND">和</SelectOption>
      <SelectOption value="OR">或</SelectOption>
    </Select>
    <Collapse :default-active-key="['1']" expandIconPosition="right" class="!my-24px">
      <CollapsePanel header="筛选器" key="1">
        <Row>
          <Col span="6">
            <p>操作</p>
          </Col>
          <Col span="4">
            <p v-show="cond.valueType === 'STRING'">忽略大小写</p>
          </Col>
          <Col span="10">
            <p>值</p>
          </Col>
        </Row>
        <Divider class="!mb-24px !mt-2px" />
        <div v-show="cond.predicate.predicates.length === 0" class="text-center"
          ><span>未配置筛选器</span></div
        >
        <div
          v-for="(item, index) in cond?.predicate.predicates"
          :key="item.id"
          class="flex items-center flex-row mb-24px"
        >
          <Select
            class="!w-full !mr-20px"
            v-model:value="item.operation"
            v-show="cond.valueType === 'STRING' && item.type != 'COMPLEX'"
            :disabled="isDisable"
          >
            <SelectOption value="EQUAL">等于</SelectOption>
            <SelectOption value="NOT_EQUAL">不等于</SelectOption>
            <SelectOption value="STARTS_WITH">开始于</SelectOption>
            <SelectOption value="ENDS_WITH">结束于</SelectOption>
            <SelectOption value="CONTAINS">包含</SelectOption>
            <SelectOption value="NOT_CONTAINS">不包含</SelectOption>
            <SelectOption value="IN">存在</SelectOption>
            <SelectOption value="NOT_IN">不存在</SelectOption>
          </Select>
          <Select
            class="!w-full !mr-20px"
            v-model:value="item.operation"
            v-show="
              (cond.valueType === 'NUMERIC' || cond.valueType === 'DATE_TIME') &&
              item.type != 'COMPLEX'
            "
            :disabled="isDisable"
          >
            <SelectOption value="EQUAL">等于</SelectOption>
            <SelectOption value="NOT_EQUAL">不等于</SelectOption>
            <SelectOption value="GREATER">大于</SelectOption>
            <SelectOption value="LESS">小于</SelectOption>
            <SelectOption value="GREATER_OR_EQUAL">大于或等于</SelectOption>
            <SelectOption value="LESS_OR_EQUAL">小于或等于</SelectOption>
          </Select>
          <Select
            class="!w-full !mr-20px"
            v-model:value="item.operation"
            v-show="
              cond.valueType === 'BOOLEAN' && item.type != 'COMPLEX' && item.type != 'COMPLEX'
            "
            :disabled="isDisable"
          >
            <SelectOption value="EQUAL">等于</SelectOption>
            <SelectOption value="NOT_EQUAL">不等于</SelectOption>
          </Select>
          <Checkbox
            v-model:checked="item.ignoreCase"
            class="!mr-20px"
            v-show="cond.valueType === 'STRING' && item?.value?.useDynamic === false"
            :disabled="isDisable"
          />
          <span v-show="item.type === 'COMPLEX'">复合筛选器</span>
          <Button
            v-show="item.type === 'COMPLEX' && !isDisable"
            size="large"
            shape="circle"
            type="text"
            @click="toEdit(item, index)"
          >
            <Icon :icon="ICON.EDIT" />
          </Button>
          <Button
            v-show="item.type === 'COMPLEX' && isDisable"
            size="large"
            shape="circle"
            type="text"
            @click="toEdit(item, index)"
          >
            <Icon :icon="ICON.MORE_Vertically" />
          </Button>
          <Input
            v-model:value="item.value.defaultValue"
            placeholder="默认值"
            v-if="cond.valueType === 'STRING' && item?.value?.useDynamic === false"
            :disabled="isDisable"
          />
          <InputNumber
            v-model:value="item.value.defaultValue"
            placeholder="默认值"
            v-if="cond.valueType === 'NUMERIC' && item?.value?.useDynamic === false"
            :disabled="isDisable"
          />
          <Checkbox
            v-model:checked="item.value.defaultValue"
            v-if="cond.valueType === 'BOOLEAN' && item?.value?.useDynamic === false"
            :disabled="isDisable"
            >真</Checkbox
          >
          <DatePicker
            show-time
            placeholder="Select Time"
            v-model:value="item.value.defaultValue"
            valueFormat="x"
            v-if="cond.valueType === 'DATE_TIME' && item?.value?.useDynamic === false"
            :disabled="isDisable"
          />
          <Select
            class="!w-full"
            v-model:value="item.value.dynamicValue.sourceType"
            placeholder="动态原类型"
            v-if="item?.value?.useDynamic === true"
            :disabled="isDisable"
            :allowClear="true"
          >
            <SelectOption value="CURRENT_TENANT">当前租户</SelectOption>
            <SelectOption value="CURRENT_CUSTOMER">当前客户</SelectOption>
            <SelectOption value="CURRENT_DEVICE">当前设备</SelectOption>
          </Select>
          <Input
            placeholder="属性源"
            v-model:value="item.value.dynamicValue.sourceAttribute"
            v-if="item?.value?.useDynamic === true"
            :disabled="isDisable"
          />
          <Checkbox
            class="!w-full"
            v-if="
              item?.value?.useDynamic === true &&
              (item.value.dynamicValue.sourceType === 'CURRENT_CUSTOMER' ||
                item.value.dynamicValue.sourceType === 'CURRENT_DEVICE')
            "
            :disabled="isDisable"
            v-model:checked="item.value.dynamicValue.inherit"
            >从所有者继承</Checkbox
          >
          <Button
            size="large"
            shape="circle"
            type="text"
            v-show="item?.value?.useDynamic === false && cond.key.type != 'CONSTANT'"
            @click="showDynamic(item)"
          >
            <Icon :icon="ICON.VARIABLE" />
          </Button>
          <Button
            size="large"
            shape="circle"
            type="text"
            v-show="item?.value?.useDynamic === true && cond.key.type != 'CONSTANT'"
            @click="hidDynamic(item)"
          >
            <Icon :icon="ICON.NUMBER" />
          </Button>
          <Button
            size="large"
            shape="circle"
            type="text"
            @click="deleteCond(index)"
            v-show="!isDisable"
          >
            <Icon :icon="ICON.X_DELETE" />
          </Button>
        </div>
      </CollapsePanel>
    </Collapse>

    <Button type="primary" @click="pushItem" class="mr-20px" v-show="!isDisable">添加</Button>
    <Button @click="toOpenAddComplex()" type="primary" v-show="!isDisable">添加复合</Button>
  </BasicModal>
  <div v-if="isAddComplex">
    <AddComplex
      @register="registerAddComplex"
      @push-out="getData"
      @edit="editData"
      :disable="isDisable"
      :isNestedSelf="true"
      :keyObj="cond.key"
      :valueType="predicateItem.valueType"
    />
  </div>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {
    Select,
    SelectOption,
    Row,
    Col,
    Input,
    Checkbox,
    Collapse,
    CollapsePanel,
    Divider,
    InputNumber,
    DatePicker,
    Button,
  } from 'ant-design-vue';
  import _ from 'lodash';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import AddComplex from '/@/components/thingsborad/sharedComponents/modules/addDeviceFileModel/Alarm/AddComplex.vue';
  import { useModal } from '/@/components/Modal';
  import { ref, nextTick, watch } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';
  const props = defineProps({
    disable: { type: Boolean }, //是否不可编辑
    keyObj: { type: Object }, //最外层key的内容
    isNestedSelf: { type: Boolean }, //是否是自身嵌套
    valueType: { type: String }, //外层的valueType
  });
  const emit = defineEmits(['push-out', 'edit']);
  let cond = ref<Recordable>({
    predicate: {
      operation: '',
      predicates: [],
    },
  });
  let isAddComplex = ref<boolean>(false);
  let isDisable = ref<boolean>(false);
  let isEdit = ref<boolean>(false);
  let whoEdit = ref<any>();
  let predicateItem = ref<Recordable>({
    key: {},
    ignoreCase: false,
    operation: 'EQUAL',
    type: '',
    value: {
      defaultValue: '',
      dynamicValue: {
        sourceType: null,
        sourceAttribute: null,
        inherit: false,
      },
      useDynamic: false,
    },
    valueType: '',
  });
  watch(
    () => props.disable,
    (nVal) => {
      isDisable.value = nVal;
    },
    { immediate: true },
  );
  const [register, { closeModal }] = useModalInner((data) => {
    if (props.isNestedSelf === true) {
      if (!data.predicates) {
        let formatData = _.cloneDeep(data);
        formatData.predicate = {
          operation: 'AND',
          type: 'COMPLEX',
          predicates: [],
        };
        predicateItem.value.valueType = props.valueType;
        formatData.key = _.cloneDeep(props.keyObj);
        predicateItem.value.key = _.cloneDeep(props.keyObj);
        if (
          props.valueType === 'STRING' ||
          props.valueType === 'NUMERIC' ||
          props.valueType === 'BOOLEAN'
        ) {
          predicateItem.value.type = props.valueType;
        }
        if (props.valueType === 'DATE_TIME') {
          predicateItem.value.type = 'NUMERIC';
        }
        if (props.valueType === 'BOOLEAN') {
          predicateItem.value.value.defaultValue = false;
        }
        cond.value = formatData;
      } else {
        isEdit.value = true;
        predicateItem.value.valueType = props.valueType;
        if (
          props.valueType === 'STRING' ||
          props.valueType === 'NUMERIC' ||
          props.valueType === 'BOOLEAN'
        ) {
          predicateItem.value.type = props.valueType;
        }
        if (props.valueType === 'DATE_TIME') {
          predicateItem.value.type = 'NUMERIC';
        }
        if (props.valueType === 'BOOLEAN') {
          predicateItem.value.value.defaultValue = false;
        }
        predicateItem.value.key = _.cloneDeep(props.keyObj);
        cond.value = _.cloneDeep(data);
        cond.value.valueType = props.valueType;
        cond.value.key = _.cloneDeep(props.keyObj);
        cond.value.predicate = _.cloneDeep(data);
        delete cond.value.predicates;
        cond.value.predicate.predicates.map((item) => {
          if (item.type != 'COMPLEX') {
            if (props.keyObj?.type != 'CONSTANT') {
              item.value.useDynamic = false;
            } else {
              item.value.useDynamic = true;
            }

            if (!item.value.dynamicValue) {
              item.value.dynamicValue = { sourceType: null, sourceAttribute: null, inherit: false };
            }
            //时间回显
            if (props.valueType === 'DATE_TIME') {
              item.value.defaultValue = dayjs(item.value.defaultValue);
            }
          }
        });
      }
    } else {
      if (!data?.predicate?.predicates) {
        let formatData = _.cloneDeep(data);
        formatData.predicate = {
          operation: 'AND',
          type: 'COMPLEX',
          predicates: [],
        };
        predicateItem.value.valueType = formatData.valueType;
        predicateItem.value.key = _.cloneDeep(formatData.key);
        if (
          data.valueType === 'STRING' ||
          data.valueType === 'NUMERIC' ||
          data.valueType === 'BOOLEAN'
        ) {
          predicateItem.value.type = data.valueType;
        }
        if (data.valueType === 'DATE_TIME') {
          predicateItem.value.type = 'NUMERIC';
        }
        if (data.valueType === 'BOOLEAN') {
          predicateItem.value.value.defaultValue = false;
        }
        cond.value = formatData;
      } else {
        isEdit.value = true;
        predicateItem.value.valueType = data.valueType;
        if (
          data.valueType === 'STRING' ||
          data.valueType === 'NUMERIC' ||
          data.valueType === 'BOOLEAN'
        ) {
          predicateItem.value.type = data.valueType;
        }
        if (data.valueType === 'DATE_TIME') {
          predicateItem.value.type = 'NUMERIC';
          data.predicate.predicates.map((item) => {
            //时间回显
            item.value.defaultValue = dayjs(item.value.defaultValue);
          });
        }
        if (data.valueType === 'BOOLEAN') {
          predicateItem.value.value.defaultValue = false;
        }
        predicateItem.value.key = _.cloneDeep(data.key);
        cond.value = _.cloneDeep(data);
      }
    }
  });
  const { createMessage } = useMessage();
  const [registerAddComplex, { openModal: openAddComplex }] = useModal();
  function toOpenAddComplex() {
    isAddComplex.value = true;
    nextTick(() => {
      openAddComplex(true, predicateItem.value);
    });
  }
  function showDynamic(data: Recordable) {
    data.value.useDynamic = true;
  }
  function hidDynamic(data: Recordable) {
    data.value.useDynamic = false;
  }
  function pushItem() {
    if (predicateItem.value.key.type != 'CONSTANT') {
      predicateItem.value.value.useDynamic = false;
    } else {
      predicateItem.value.value.useDynamic = true;
    }
    cond.value.predicate.predicates.push(_.cloneDeep(predicateItem.value));
  }
  function deleteCond(index: number) {
    cond.value.predicate.predicates.splice(index, 1);
  }
  function getData(data: Recordable) {
    cond.value.predicate.predicates.push(_.cloneDeep(data.predicate));
  }
  function toEdit(data: Recordable, index: number) {
    isAddComplex.value = true;
    whoEdit.value = index;
    nextTick(() => {
      openAddComplex(true, data);
    });
  }
  function editData(data: Recordable) {
    if (cond.value.predicates) {
      cond.value.predicates[whoEdit.value] = _.cloneDeep(data);
    } else {
      cond.value.predicate.predicates[whoEdit.value] = _.cloneDeep(data);
    }
    isAddComplex.value = false;
  }
  function save() {
    let hasEmpty = false;
    if (!cond.value.predicate.predicates.length) {
      createMessage.error('请添加筛选器');
      hasEmpty = true;
    }
    if (predicateItem.value.key.type === 'CONSTANT') {
      cond.value.predicate.predicates.map((item) => {
        if (
          item.type != 'COMPLEX' &&
          (!item.value.dynamicValue.sourceType || !item.value.dynamicValue.sourceAttribute)
        ) {
          createMessage.error('属性源不能为空');
          hasEmpty = true;
          return;
        }
      });
    }
    if (hasEmpty) {
      return;
    }
    if (isEdit.value) {
      if (props.isNestedSelf === true) {
        cond.value.predicates = cond.value.predicate.predicates;
        delete cond.value.predicate;
        delete cond.value.valueType;
        delete cond.value.key;
      }

      emit('edit', cond.value);
    } else {
      emit('push-out', cond.value);
    }
    closeModal();
  }
</script>
<style lang="less" scoped>
  :deep(.ant-checkbox-wrapper) {
    span {
      white-space: nowrap;
    }
  }
</style>
